package com.xg.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

/**
 * @author MI
 * @ClassName VariableUtils.java
 * @createTime 2021年09月03日 16:42:00
 */
public class VariableUtils {
    /**
     * 获取参数，主要是LED发送时使用(${name} )
     *
     * @return
     */
    public static String getVariable(String variable, JSONObject body) {
        String str = variable;
        if (StringUtils.isNotBlank(variable)) {
            if (StringUtils.containsAny(variable, "${", "{")) {
                variable = StringUtils.replaceEach(variable, new String[]{"${", "{", "}"}, new String[]{"", "", ""});
                if (body.containsKey("param")) {
                    str = body.getString("param");
                }
                if (body.containsKey(variable)) {
                    str = body.getString(variable);
                }
            }
        }
        return str;
    }

    public static String getVariableJson(String variable, String strJson) {
        String str = strJson;
        if (StringUtils.startsWith(strJson, "{")) {
            JSONObject jsonObject = JSON.parseObject(strJson);
            str = StringUtils.isNotBlank(jsonObject.getString(variable)) ? jsonObject.getString(variable) : "";
        }
        return str;
    }

}
